package org.cweili.rayminder.servlet

import org.apache.commons.lang3.StringEscapeUtils
import org.apache.commons.lang3.StringUtils
import org.cweili.rayminder.util.Beans
import org.cweili.rayminder.util.Global
import org.cweili.rayminder.util.Utils

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
/**
 *
 * @author Cweili
 * @version 13-8-29 下午9:10
 *
 */
class DispatcherServlet extends BaseServlet {

	static final POST = 'Post'
	static final PATH = Global.APP_CONTEXT_PATH
	static final INDEX = 'index'
	static final char SEPARATOR = '/'

	@Override
	protected process(HttpServletRequest req, HttpServletResponse resp) {
		log.info("Begin request: [$req.requestURI]")
		resp.setHeader('Content-Type', 'text/html;charset=' + Global.CHARSET)
		def out = resp.outputStream
		if (req.requestURI == PATH) {
			// 首页
			out.write(invoke(INDEX, null, null))
			return
		}
		def reqPaths = StringUtils.split(req.requestURI.substring(PATH.length()), SEPARATOR)
		def paramMap = [:]
		for (entry in req.parameterMap.entrySet()) {
			def val
			if (entry.value.length > 1) {
				val = Utils.json(entry.value)
			} else {
				val = StringUtils.trimToEmpty(StringEscapeUtils.escapeHtml4(entry.value[0]))
			}
			paramMap.put(entry.key, val)
		}
		if (reqPaths.length > 0) {
			def method = (reqPaths.length > 1 ? reqPaths[1] : INDEX) +
					(req.method.equalsIgnoreCase(POST) ? POST : '')
			out.write(invoke(reqPaths[0], method, paramMap))
		}
		log.info("End request: [$req.requestURI]")
	}

	private invoke(String controller, String method, Map param) {
		param = param?.size() > 0 ? param : null
		param && log.info("params: $param")
		try {
			Beans.get(controller + 'Controller').invokeMethod(method ?: INDEX, param)
					.toString().getBytes(Global.CHARSET)
		} catch (Exception e) {
			Utils.error(e)
		}
	}
}
